package jdbc.test;

import cn.myschool.java79.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
//银行转账
public class BankTransfer {
    public static void main(String[] args) {
        transfer("chenxu","zhangjun",200);
    }
    public static void transfer(String from,String to,float money){
        Connection con = null;
        PreparedStatement ps = null;
        PreparedStatement ps2 = null;
        String sql="update bank set balance=balance-? where ano=?";
        String sql2="update bank set balance=balance+? where ano=?";
        try {
            con = DBUtil.getConnection();
            con.setAutoCommit(false);
            ps=con.prepareStatement(sql);
            ps.setFloat(1,money);
            ps.setString(2,from);
            int d1 = ps.executeUpdate();

            ps2=con.prepareStatement(sql2);
            ps2.setFloat(1,money);
            ps2.setString(2,to);
            int d2=ps2.executeUpdate();
            System.out.println(d1+","+d2);
            if(d1>0 &&d2>0)
                con.commit();
            else
                con.rollback();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(ps);
            DBUtil.close(ps2);
            DBUtil.close(con);
        }
    }
}
